﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
using RestaurateurConsole;
using RestaurateurConsole.Core;

namespace RestaurateurGUI
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            HandlerFactory factory = new HandlerFactory();
            DishesHandler dishes = factory.GetDishesHandler();
            CustomerHandler accounts = factory.GetCustomerHandler();
            ActivityHandler activities = factory.GetActivityHandler();
            SalesHandler sales = factory.GetSalesHandler();
            SoldItemsHandler soldItemsHandler = factory.GetSoldItemsHandler();
            Form toRun = null;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            string currentProc = Environment.CommandLine.Substring(Environment.CommandLine.LastIndexOf("\\") + 1).Replace("\"", "").Trim().Replace(".exe", "").Replace(".EXE", "");
            Process[] runningInstances = Process.GetProcessesByName(currentProc);
            if (runningInstances.Count() > 1)
                toRun = new WillNotRun("Another instance of this application is already open.", true);

            Form mainForm = null;
            if (toRun == null)
            {
                try
                {
                    if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
                        BackupHandler.Backup(factory.GetDatabase());
                }
                catch { }

                mainForm = new MainForm(dishes, accounts, activities, sales, soldItemsHandler, factory.GetDatabase());
                if (ConfigHandler.Configuration.RegistrationKey == "" && ConfigHandler.Configuration.RegistrationKey != "FE22GA11RO44BY88")
                {
                    if (DateTime.Now > new DateTime(2008, 6, 30))
                        toRun = new WillNotRun("Evaluation period expired; please enter registration key.", mainForm);
                    else if (DateTime.Now < ConfigHandler.Configuration.LastRunDate)
                        toRun = new WillNotRun("System date tampered with; please enter registration key.", mainForm);
                    else if (ConfigHandler.Configuration.RegistrationKey != "FE22GA11RO44BY88")
                        toRun = new WillNotRun("Invalid registration key; please enter registration key.", mainForm);
                    else
                    {
                        ConfigHandler.Configuration.LastRunDate = DateTime.Now;
                        ConfigHandler.Configuration.Save();
                    }
                }
                if (toRun != null)
                {
                    //Try to see if the application was ever registered.
                    string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    string key = "";
                    bool wasRegisteredBefore = false;
                    if (new DirectoryInfo(Desktop).GetDirectories("Restaurateur Data Backup").Length != 0)
                    {
                        var backupDir = new DirectoryInfo(Desktop).GetDirectories("Restaurateur Data Backup")[0].GetDirectories().OrderByDescending(D => D.CreationTime).AsEnumerable();
                        wasRegisteredBefore = false;
                        foreach (DirectoryInfo dir in backupDir)
                        {
                            FileInfo[] config = dir.GetFiles("RestaurateurMenu.config");
                            if (config.Length == 1)
                            {
                                FileStream f = config[0].Open(FileMode.Open);
                                BinaryFormatter b = new BinaryFormatter();
                                Config c = null;
                                try
                                {
                                    c = b.Deserialize(f) as Config;
                                }
                                catch { }
                                f.Close();
                                if (c != null)
                                {
                                    if (WillNotRun.IsValidKey(c.RegistrationKey))
                                    {
                                        key = c.RegistrationKey;
                                        RestaurateurConsole.ConfigHandler.Configuration.NoOfTables = c.NoOfTables;
                                        RestaurateurConsole.ConfigHandler.Configuration.PhoneNumber = c.PhoneNumber;
                                        RestaurateurConsole.ConfigHandler.Configuration.TaxRate = c.TaxRate;
                                        RestaurateurConsole.ConfigHandler.Configuration.TaxAdditionThreshhold = c.TaxAdditionThreshhold;
                                        wasRegisteredBefore = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    if (wasRegisteredBefore)
                    {
                        if (WillNotRun.IsValidKey(key))
                        {
                            ConfigHandler.Configuration.RegistrationKey = key;
                            ConfigHandler.Configuration.Save();
                            (mainForm as RestaurateurGUI.MainForm).toolStripMenuItem3_Click(null, null);
                            (mainForm as RestaurateurGUI.MainForm).SetStatusText("The application recovered from a corrupted configuration database using data backups.");
                            Application.Run(mainForm);
                        }
                    }
                    else
                    {
                        Application.Run(toRun);
                    }
                }
                else
                    Application.Run(mainForm);
                }
            else
                Application.Run(toRun);
        }
    }
}
